﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using CashAgent.Biz;
using CashAgent.Model;
using Newtonsoft.Json;
using System.Configuration;

namespace CashAgent
{
    public partial class FrmMain : Form
    {

        public FrmMain()
        {
            InitializeComponent();
        }

        string _storeId = "";


        //更新菜单
        private void btnUpdateFood_Click(object sender, EventArgs e)
        {
            DicData dicData = new DicData();
            DataTable dt = dicData.GetFoodList();

            //菜单分类
            List<EntityFoodCategory> foodCategories = new List<EntityFoodCategory>();
            //菜品
            List<EntityFood> foods = new List<EntityFood>();
            //套餐
            List<EntityPackageFood> packageFoods = new List<EntityPackageFood>();

            foreach (DataRow dataRow in dt.Rows)
            {
                //封装菜单分类
                if (foodCategories.Where(p => p.foodCategoryCode == Convert.ToString(dataRow["foodCategoryCode"])).Count() == 0)
                {
                    #region 封装菜单分类
                    EntityFoodCategory foodCategory = new EntityFoodCategory();
                    foodCategory.foodCategoryCode = Convert.ToString(dataRow["foodCategoryCode"]);
                    foodCategory.foodCategoryName = Convert.ToString(dataRow["foodCategoryName"]);
                    foodCategories.Add(foodCategory);
                    #endregion
                }

                //封装菜品
                if (Convert.ToInt32(dataRow["isSetFood"]) == 0)
                {
                    #region 封装菜品
                    if (foods.Where(p => p.unitCode == Convert.ToString(dataRow["unitCode"])).Count() == 0)
                    {
                        EntityFood food = new EntityFood();
                        food.foodCategoryName = Convert.ToString(dataRow["foodCategoryName"]);
                        food.allowCouponDis = 0;
                        food.allowSingleDis = 0;
                        food.allowCardDisType = 2;
                        food.foodName = Convert.ToString(dataRow["foodName"]);
                        food.originalPrice = GetPrice(Convert.ToString(dataRow["originalPrice"]));
                        food.price = GetPrice(Convert.ToString(dataRow["Price"]));
                        food.unit = Convert.ToString(dataRow["unit"]);
                        food.unitCode = Convert.ToString(dataRow["unitCode"]);
                        food.vipPrice = GetPrice(Convert.ToString(dataRow["vipPrice"]));
                        foods.Add(food);
                    }
                    #endregion
                }
                else
                {
                    #region 封装套餐
                    if (Convert.ToInt32(dataRow["isSetFoodDetail"]) == 0 &&
                        packageFoods.Where(p => p.unitCode == Convert.ToString(dataRow["SFMUnitCode"])).Count() == 0)//这里需要按照套餐代码分类
                    {
                        #region 封装套餐主信息
                        EntityPackageFood packageFood = new EntityPackageFood();
                        packageFood.allowCouponDis = 0;
                        packageFood.allowSingleDis = 0;
                        packageFood.allowCardDisType = 2;
                        packageFood.foodName = Convert.ToString(dataRow["foodName"]);
                        packageFood.originalPrice = Convert.ToDecimal(dataRow["originalPrice"]);
                        packageFood.price = Convert.ToDecimal(dataRow["Price"]);
                        packageFood.unit = Convert.ToString(dataRow["unit"]);
                        packageFood.unitCode = Convert.ToString(dataRow["unitCode"]);
                        packageFood.vipPrice = Convert.ToDecimal(dataRow["vipPrice"]);
                        packageFoods.Add(packageFood);
                        #endregion
                    }
                    else
                    {
                        #region 封装套餐明细
                        var packFood = packageFoods.Find(p => p.unitCode == Convert.ToString(dataRow["SFMUnitCode"]));
                        if (packFood.subFoods == null)
                        {
                            packFood.subFoods = new List<EntitySubFood>();
                        }
                        EntitySubFood subFood = new EntitySubFood();
                        subFood.addPrice = Convert.ToDecimal(dataRow["addPrice"]);
                        subFood.everyQuantity = 0;
                        subFood.foodName = Convert.ToString(dataRow["foodName"]);
                        subFood.selectMaxNum = 1;
                        packFood.subFoods.Add(subFood);
                        #endregion
                    }
                    #endregion
                }
            }

            List<string> jsonCategories = GetJsonData(foodCategories);
            foreach (var item in jsonCategories)
            {
                RequestUtil.Reqest("/open/cashier/category/update", GetJsonContent(item));
            }

            List<string> jsonFoods = GetJsonData(foods);
            foreach (var item in jsonFoods)
            {
                RequestUtil.Reqest("/open/cashier/goods/update", GetJsonContent(item));
            }

            List<string> jsonPackFoods = GetJsonData(packageFoods);
            foreach (var item in jsonPackFoods)
            {
                RequestUtil.Reqest("/open/cashier/package/update", GetJsonContent(item));
            }

        }

        //更新沽清
        private void btnUpdateSellOut_Click(object sender, EventArgs e)
        {
            DicData dicData = new DicData();
            DataTable dt = dicData.GetSellClearFoodList();

            List<EntitySellClearFood> sellClearFoods = new List<EntitySellClearFood>();
            foreach (DataRow dataRow in dt.Rows)
            {
                EntitySellClearFood clearFood = new EntitySellClearFood();
                clearFood.foodName = Convert.ToString(dataRow["foodName"]);
                clearFood.estimateNum = Convert.ToDecimal(dataRow["Qty"]);
                sellClearFoods.Add(clearFood);
            }
            List<string> jsonClearFoods = GetJsonData(sellClearFoods);
            foreach (var item in jsonClearFoods)
            {
                RequestUtil.Reqest("/open/cashier/goods/estimate", GetJsonContent(item));
            }

        }

        //更新桌台
        private void btnUpdateTable_Click(object sender, EventArgs e)
        {
            DicData dicData = new DicData();
            DataTable dt = dicData.GetTableList();
            List<EntityTable> tables = new List<EntityTable>();
            foreach (DataRow dataRow in dt.Rows)
            {
                EntityTable table = new EntityTable();
                table.tableName = Convert.ToString(dataRow["TableName"]);
                table.number = Convert.ToInt32(dataRow["defaultPerson"]);
                tables.Add(table);
            }

            List<string> jsonTables = GetJsonData(tables);
            foreach (var item in jsonTables)
            {
                RequestUtil.Reqest("/open/cashier/table/update", GetJsonContent(item));
            }
        }


        /// <summary>
        /// 拼接成接口所需的Json格式
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        private string GetJsonContent(string jsonData)
        {
            return string.Format("{0}\"data\":{1},\"storeId\":\"{2}\"{3}", "{", jsonData, _storeId, "}");
        }

        /// <summary>
        /// 拆分成每个100条的集合并转换成json格式List返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dataList"></param>
        /// <returns></returns>
        private List<string> GetJsonData<T>(List<T> dataList)
        {
            List<string> jsonList = new List<string>();
            double pagenumber = Math.Ceiling(dataList.Count / 100d);//页数 
            int pagesize = 100;//每份数据大小
            for (int i = 0; i < pagenumber; i++)
            {
                List<T> item = null;
                if (dataList.Count - i * 100 < 100)
                {
                    item = dataList.Cast<T>().Skip(pagesize * (i)).Take(pagesize).ToList<T>();
                }
                else
                {
                    item = dataList.Cast<T>().Skip(pagesize * (i)).Take(pagesize).ToList<T>();
                }


                jsonList.Add(JsonConvert.SerializeObject(item));

            }
            return jsonList;
        }

        private decimal GetPrice(string price)
        {
            //多个价格商品拆分后取第一个
            string[] priceArray = price.Split('|');
            if (priceArray.Length > 0)
                return Convert.ToDecimal(priceArray[0]);

            return Convert.ToDecimal(price);
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            _storeId = ConfigurationManager.AppSettings["storeId"].ToString();
            lbStoreName.Text = ConfigurationManager.AppSettings["storeName"].ToString();
        }

    }
}
